<template>
  <div id="qcinstritemDiv">
    <Breadcrumb content="仪器质控项目设定" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="20">
          <!-- <el-table
            ref="instrTableRef"
            :data="instrList"
            v-loading="instrLoading"
            @row-click="clickRowSelect"
            highlight-current-row
            row-key="id"
            border
            default-expand-all
          >
            <el-table-column prop="instr" label="编码" sortable />
            <el-table-column prop="instrName" label="名称" sortable />
          </el-table> -->

          <vxe-table ref="instrTableRef" class="mytable-scrollbar" border align="center" height="auto" :data="instrList" :loading="instrLoading" @current-change="clickRowSelect" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true, keyField: 'id' }" :column-config="{ resizable: true }" :tree-config="{
              expandAll: true,
              rowField: 'id'
            }" resizable show-overflow keep-source :reserve="true">
            >
            <vxe-column field="instrCode" title="编码" tree-node sortable></vxe-column>
            <vxe-column field="instrName" title="名称" sortable></vxe-column>
          </vxe-table>
        </Pane>
        <Pane size="80">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">质控项目设定</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :disabled="disabledTag" :loading="qloading" @click="findQcInstrItemList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" :disabled="disabledTag" @click="addQcInstrItemDialog()"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveInstrItemList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="qcItemTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="qcItemList" :loading="qloading" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30" align="center"></vxe-column>
              <vxe-column field="itemDictCode" title="质控项目编码" width="200"> </vxe-column>
              <vxe-column field="itemDictName" title="质控项目名称" width="230"> </vxe-column>
              <vxe-column field="itemDefine" title="项目定义" width="150" :edit-render="{}">
                <template #default="{ row }">
                  <span>{{ formatCommon(itemDefineList, row.itemDefine) }}</span>
                </template>
                <template #edit="{ row, rowIndex, column }">
                  <!-- 选择字典  -->
                  <vxe-select v-model="row.itemDefine">
                    <vxe-option v-for="hobj in itemDefineList" :key="hobj.id" :value="hobj.code" :label="hobj.name"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="140"> </vxe-column>
              <vxe-column field="isEdit" title="在用">
                <template #default="{ row, rowIndex, column }">
                  <el-tag :type="getStatusTagType(row)">{{ getStatusDesc(row) }}</el-tag>
                </template>
              </vxe-column>
            </vxe-table>
          </div>

          <el-dialog title="报告项目" :show-close="false" v-model="showDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showDialog">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findLabItemList2" @keyup="keyupEnter" @search-click="findLabItemList2()"></vxe-input>
                <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findLabItemList2"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="tableBody" style="height: 600px">
              <vxe-table ref="labItemTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="labItemList" :loading="lloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>
                <vxe-column title="序号" width="80">
                  <template #default="{ row, rowIndex, column }">
                    <span>{{ rowIndex + 1 }}</span>
                  </template>
                </vxe-column>
                <vxe-column type="checkbox" width="30px"></vxe-column>
                <vxe-column field="itemNo" title="项目代码"></vxe-column>
                <vxe-column field="itemNa" title="项目名称"></vxe-column>
                <vxe-column field="itemClass" title="项目归类" width="60">
                  <template #default="{ row }">
                    <span>{{ formatCommon(itemClassDict, row.itemClass) }}</span>
                  </template>
                </vxe-column>
                <vxe-column field="instrClass" title="仪器大类" width="60">
                  <template #default="{ row }">
                    <span>{{ formatCommon(instrClassDict, row.instrClass) }}</span>
                  </template>
                </vxe-column>
                <vxe-column field="rptGroupName" title="报告单元"></vxe-column>
                <vxe-column field="itemEnCode" title="缩写"></vxe-column>
                <vxe-column field="unit" title="单位"></vxe-column>
              </vxe-table>

              <div class="dialog-footer flex right justify-end">
                <el-button type="primary" @click="saveBacthQcItem('qcItemTableRef')">确定</el-button>
                <el-button @click="closeDialog('qcItemTableRef')">取消</el-button>
              </div>
            </div>
          </el-dialog>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示

// 全局变量区 =============
let instrList: any = reactive([]); //左侧仪器表格数据
let sltInstr: any = reactive({});
let qcItemList: any = reactive([]); //右侧质控项目表格数据
let labItemList: any = reactive([]); //弹框表格数据
const itemClassDict = reactive([]); //项目类型字典
const instrClassDict = reactive([]); //仪器大类字典
let instrLoading = ref(false); //左侧仪器表格加载
let qloading = ref(false); //右侧质控表格加载+刷新
let lloading = ref(false); //弹框表格数据加载状态
let disabledTag = ref(true); //中间质控品维护按钮标记
let showDialog = ref(false); //添加弹框展示状态
let itemDefineList: any = reactive([]); //左侧对应质控水平选择字典
let searchForm = reactive({
  searchValue: ''
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  getDictItemsList(); //批量获取字典 包含了(项目归类/仪器大类)
  findInstrList(); // 获取左侧仪器表格数据
});
let dictTreeTypeCodes: any = reactive(['reportCategory', 'YQDL', 'LABITEMKIND', 'QCItemDefine']);

//批量获取字典
async function getDictItemsList() {
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  let itemClassType = dictTreeTypeItems.data.find((item) => item.code === 'reportCategory');
  itemClassDict.push(...itemClassType.detailDataList);

  const instrClassType = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassDict.push(...instrClassType.detailDataList);
  const iDefineType = dictTreeTypeItems.data.find((item) => item.code === 'QCItemDefine');
  itemDefineList.push(...iDefineType.detailDataList);
}

// 获取左侧仪器表格数据
function findInstrList() {
  instrList.length = 0; //放入数据前清空数据
  instrLoading.value = true;
  const url = '/api/qc/qcInstrItem/findInstrClassAndInstrList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '', poct: 1 }
    })
    .then((res: any) => {
      instrList.push(...res.data);
      if (instrList.length > 0) {
        const sltObj = getChildren(instrList[0]);
        sltInstr = sltObj;
        setCurTypeNode(sltObj); //定位当前行
        clickRowSelect({ row: sltInstr }); //点击当前行获取右侧质控项目表格数据
      }
      instrLoading.value = false;
    })
    .catch((err: any) => {
      instrLoading.value = false;
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

// 获取children那条数据
function getChildren(obj: any) {
  const children = obj.children;
  return children[0];
}

// 光标定位在左侧仪器表格上
function setCurTypeNode(sltObj: any) {
  proxy.$nextTick(() => {
    const treeName = 'instrTableRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentRow(sltObj);
  });
}

// 左侧仪器点击当前行
function clickRowSelect({ row }) {
  const isSearch = row.isSearch;
  if (isSearch == '0') {
    sltInstr = row;
    findQcInstrItemList(); // 右侧获取质控项目表格数据
  } else {
    qcItemList.length = 0;
    sltInstr = reactive({});
  }
  //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
  if (!sltInstr.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
  }
}

// 右侧获取质控项目表格数据
function findQcInstrItemList() {
  if (IsEmpty(sltInstr)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    qloading.value = true;
    qcItemList.length = 0; //放入数据前清空数据
    const url = '/api/qc/qcInstrItem/findQcInstrItemList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { pid: sltInstr.id }
      })
      .then((res: any) => {
        qcItemList.push(...res.data);
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}

// 获取是否静态的tag标记(绿/红)
function getStatusTagType(row: any) {
  if (row.status == '0') {
    return 'success';
  } else if (row.status == '1') {
    return 'danger';
  }
}
// 获取是否静态文字(是/否)
function getStatusDesc(row: any) {
  if (row.status == '0') {
    return '是';
  } else if (row.status == '1') {
    return '否';
  }
}

// 添加按钮
function addQcInstrItemDialog() {
  if (IsEmpty(sltInstr)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    findLabItemList();
    showDialog.value = true;
  }
}

// 删除按钮
function handleDelete() {
  const sltQcItems = (proxy.$refs.qcItemTableRef as any).getCheckboxRecords();
  if (!(sltQcItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { qcInstrItemList: sltQcItems };
        const url = '/api/qc/qcInstrItem/batchDeleteQcInstrItemList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findQcInstrItemList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findLabItemList2();
  }
}

// 获取弹框表格数据
function findLabItemList() {
  lloading.value = true;
  labItemList.length = 0; //放入数据前清空数据
  const url = '/lis/lab/item/findJoinLabItemDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        instrClass: sltInstr.instrClass,
        rptGroup: sltInstr.rptGroup,
        searchValue: searchForm.searchValue
      }
    })
    .then((res: any) => {
      labItemList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

function findLabItemList2() {
  lloading.value = true;
  labItemList.length = 0; //放入数据前清空数据
  const url = '/lis/lab/item/findJoinLabItemDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        instrClass: sltInstr.instrClass,
        rptGroup: sltInstr.rptGroup,
        searchValue: searchForm.searchValue
      }
    })
    .then((res: any) => {
      labItemList.push(...res.data);
      const itemDictIds = qcItemList.map((m) => m.itemDictId);
      const ilist = labItemList.filter((p: any) => itemDictIds.includes(p.id));
      const $table = proxy.$refs.labItemTableRef;
      $table.setCheckboxRow(ilist, true);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = qcItemList.filter((p: any) => {
    defaultSelecteRowKeys.push(p.itemDictId);
    return p.itemDictId == row.id;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = qcItemList.filter((p: any) => {
    // return p.itemDictId == row.id;
  });
  return obj.length == 0;
}

// 弹框保存的确定按钮
function saveBacthQcItem() {
  const selectRows = (proxy.$refs.labItemTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addQcItemList = [];
    for (const sltRow of selectRows) {
      const qcitem = qcItemList.find((qc: any) => qc.itemDictId == sltRow.id);
      if (IsEmpty(qcitem)) {
        const addQcItem = {
          instrId: sltInstr.id,
          itemDictId: sltRow.id,
          itemDefine: 'dl',
          status: 0,
          seq: sltRow.seq
        };
        addQcItemList.push(addQcItem);
      }
    }
    if (addQcItemList.length > 0) {
      const data = { qcInstrItemList: addQcItemList };
      const url = '/api/qc/qcInstrItem/batchAddQcInstrItemList';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          findQcInstrItemList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  }
  closeDialog();
}

async function saveInstrItemList() {
  console.log('111');

  let $Xtable = proxy.$refs.qcItemTableRef as any;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    console.log(updateRecords);

    const sveOrupdateSamples = [] as any[];
    updateRecords.forEach((e: any) => {
      const iISample: any = {
        id: e.id,
        instrId: e.instrId,
        itemDictId: e.itemDictId,
        status: e.status,
        itemDefine: e.itemDefine,
        seq: e.seq,
        orgId: e.orgId
      };

      sveOrupdateSamples.push(iISample);
    });

    if (sveOrupdateSamples.length > 0) {
      const url = '/api/qc/qcInstrItem/batchUpdateQcInstrItemList';
      const obj: any = {};
      obj.qcInstrItemList = sveOrupdateSamples;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findQcInstrItemList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}

// 弹框取消按钮
function closeDialog() {
  searchForm.searchValue = '';
  showDialog.value = false;
}
// 表格 项目归类/仪器大类/结果类型 格式化
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
// ---------------------------------------------------
//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#qcinstritemDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
    }
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    //右侧质控项目表格
    .tableBox {
      height: calc(100% - 40px);
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;

      .dialog-footer {
        height: 40px;
      }
    }
  }
}
</style>
